<?php
namespace api\modules\v1\models;

use yii\base\Model;

class FtpForm extends Model
{

    public $host;

    public $port;

    public $timeout;

    public $ftp_stream;

    public $username;

    public $password;

    public $pasv;

    public function __construct()
    {
        $this->host = '203.171.232.86';
//         $this->host = '127.0.0.1';
        $this->port = 21;
        $this->timeout = 10;
        $this->username = 'upload';
        $this->password = 'upload';
        $this->pasv = true;
        $this->ftp_stream = @ftp_connect($this->host, $this->port, $this->timeout);
        if (! $this->ftp_stream) {
            $this->addError('message', 'FTP连接失败！');
        }
        if (! @ftp_login($this->ftp_stream, $this->username, $this->password)) {
            $this->addError('message', 'FTP登陆失败！');
        }
        if(! @ftp_pasv($this->ftp_stream, $this->pasv)){
            $this->addError('message', 'FTP服务器未开启被动传输模式！');
        }
    }

    public function put($remote_file, $local_file, $mode = FTP_BINARY, $startpos = null)
    {
        $this->mkdir(dirname($remote_file));
        if(! @ftp_put($this->ftp_stream, $remote_file, $local_file, $mode, $startpos)){
            $this->addError('message', 'FTP上传文件失败，请检查服务器权限！');
        }
    }

    public function delete($path)
    {
        return @ftp_delete($this->ftp_stream, $path);
    }

    public function mkdir($directory)
    {
        return @ftp_mkdir($this->ftp_stream, $directory);
    }

    public function __destruct()
    {
        @ftp_close($this->ftp_stream);
    }
}